package com.hsurosy.domain.strategy.service.rule.tree.impl;

import com.hsurosy.domain.strategy.model.valobj.RuleLogicCheckTypeVO;
import com.hsurosy.domain.strategy.model.valobj.StrategyAwardStockKeyVO;
import com.hsurosy.domain.strategy.repository.IStrategyRepository;
import com.hsurosy.domain.strategy.service.armory.IStrategyDispatch;
import com.hsurosy.domain.strategy.service.rule.tree.ILogicTreeNode;
import com.hsurosy.domain.strategy.service.rule.tree.factory.DefaultTreeFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Author Hsu琛君珩
 * @Date 2024-10-19 15:27
 * @Description 库存节点逻辑处理类
 * @Version: v1.0.0
 */
@Slf4j
@Component("rule_stock")
public class RuleStockLogicTreeNode implements ILogicTreeNode {

    @Resource
    private IStrategyDispatch strategyDispatch;

    @Resource
    private IStrategyRepository strategyRepository;

    /**
     * 规则过滤-库存扣减逻辑
     *
     * @param userId 用户ID
     * @param strategyId 抽奖策略ID
     * @param awardId 奖品ID
     * @param ruleValue 当前规则值（此处不使用，可为空）
     * @return TreeActionEntity 包含规则检查结果和最终奖品数据
     */
    @Override
    public DefaultTreeFactory.TreeActionEntity logic(String userId, Long strategyId, Integer awardId, String ruleValue) {
        log.info("规则过滤-库存扣减 userId:{} strategyId: {} awardId: {}", userId, strategyId, awardId);

        // 1. 执行库存扣减操作，通过 strategyDispatch 进行奖品库存的扣减
        Boolean status = strategyDispatch.subtractionAwardStock(strategyId, awardId);

        // 2. 如果扣减成功，接管抽奖流程，返回扣减后的奖品信息
        if (status) {
            log.info("规则过滤-库存扣减-成功 userId:{} strategyId:{} awardId:{}", userId, strategyId, awardId);

            // 2.1 扣减成功后，将扣减信息写入延迟队列
            // 延迟队列用于延迟更新数据库的库存信息，在队列被消费时更新数据库记录
            strategyRepository.awardStockConsumeSendQueue(StrategyAwardStockKeyVO.builder()
                    .strategyId(strategyId)
                    .awardId(awardId)
                    .build());

            // 2.2 返回扣减后的奖品信息，并接管流程
            return DefaultTreeFactory.TreeActionEntity.builder()
                    .ruleLogicCheckType(RuleLogicCheckTypeVO.TAKE_OVER)  // 接管流程
                    .strategyAwardVO(DefaultTreeFactory.StrategyAwardVO.builder()
                            .awardId(awardId)  // 扣减后的奖品ID
                            .awardRuleValue("")  // 规则值，暂时为空
                            .build())
                    .build();
        }

        // 3. 如果库存不足或扣减失败，允许后续规则继续处理
        log.info("规则过滤-库存扣减-失败 userId:{} strategyId:{} awardId:{}", userId, strategyId, awardId);
        return DefaultTreeFactory.TreeActionEntity.builder()
                .ruleLogicCheckType(RuleLogicCheckTypeVO.ALLOW)  // 继续后续规则处理
                .build();
    }

}
